import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread("E:\opencv\opencv\sources\samples\data\mili.jpg")

grayImg = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#blurImg = cv2.GaussianBlur(grayImg,(5,5),0)
#ret,threshImg = cv2.threshold(grayImg,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
th3 = cv2.adaptiveThreshold(grayImg,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,101,1)
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
th3  = cv2.morphologyEx(th3,cv2.MORPH_OPEN,kernel)

#copyImg = threshImg.clone()
cnts,hie = cv2.findContours(th3,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(th3,cnts,-1,(120,0,0),2)

count = 0
area_avrg = 0
array = []
arr = [1,2]
for cnt in cnts:
    area = cv2.contourArea(cnt)
    if area < 10:
        continue
    count += 1
    area_avrg += area
    array.append(area)
    print('{}-blob:{}'.format(count,area),end='  ')
    rect = cv2.boundingRect(cnt)
    cv2.rectangle(image,rect,(0,0,255),1)
    y = 10 if rect[1] < 10 else rect[1]
    cv2.putText(image,str(count),(rect[0],y),cv2.FONT_HERSHEY_COMPLEX,0.4,(0,255,0),1)
print('米粒平均面积:{}'.format(round(area_avrg/area,2)))
print('均值',np.mean(array))
print('方差',np.var(array))

cv2.imshow('image',image)
cv2.imshow('th3',th3)
cv2.waitKey(0)